package work.chief.servlet;

import work.chief.utils.VerifyCodeUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "codeServlet", urlPatterns="/codeServlet")
public class CodeServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //禁止一切缓存
        resp.setHeader("Pragma","No-cache");
        resp.setHeader("Cache-Control","no-cache");
        //实时更新
        resp.setDateHeader("Expires",0);
        //表示响应格式为图片
        resp.setContentType("image/jpeg");
        //生成验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);

        /**
         *获取session对象
         * session存储验证码（键值对形式）
         */
        HttpSession session =req.getSession();
        session.setAttribute("code",code);


        //服务器生成一张图片，发送给客户端
        int width=200;
        int height=80;
        VerifyCodeUtils.outputImage(width,height,resp.getOutputStream(),code);
    }
}
